# timerfd 是什么
timerfd 是一个时间相关的 fd,当 timerfd 初始化时,可以设置一个超时时间,超时之后,该句柄可读,读出来的是超时的次数。
timerfd 使用起来比较简单,我们把他的用法过一遍即可:
# timerfd 的使用
timerfd 相关的系统调用有 3 个:
// 创建一个 timerfd 句柄
int timerfd_create(int clockid, int flags);
// 启动或关闭 timerfd 对应的定时器
int timerfd_settime(int fd, int flags, const struct itimerspec *new_value, struct itimerspec *old_value);
// 获取指定 timerfd 距离下一次超时还剩的时间
int timerfd_gettime(int fd, struct itimerspec *curr_value);
1
2
3
4
5
6
2
3
4
5
6
timerfd 常与 epoll 系统调用结合使用:
// 创建一个 timerfd 句柄
int fdTimer = timerfd_create(CLOCK_MONOTONIC, 0 /*flags*/);
itimerspec timespec {
// 设置超时间隔
.it_interval = {
.tv_sec = 5,
.tv_nsec = 0,
},
//第一次超时时间
.it_value = {
.tv_sec = 5,
.tv_nsec = 0,
},
};
//启动定时器
int timeRes = timerfd_settime(fdTimer, 0 /*flags*/, ×pec, nullptr);
//初始化 fd
mEpollFd = epoll_create(1024);
if (epollfd == -1) {
perror("epoll_create");
exit(EXIT_FAILURE);
}
// epoll 监听 timerfd
epoll_ctl(mEpollFd, EPOLL_CTL_Add, fdTimer, &eventItem);
while (true)
{
// 进入休眠状态
epoll_wait(mEpollFd, eventItems, EPOLL_MAX_EVENTS, timeoutMillis);
if (count < 0)
{
perror("epoll failed");
break;
}
for (int i=0;i < count;i++)
{
//处理计时器到达事件
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44